<template>
  <div>
  <base-modal
    :show.sync="visible"
    :title="$t('common.base.statistics')"
    width="1000px"
    class="statistical-dialog"
    @closed="onClose('form')"
  >
    <div class="base-modal-content">
      <div class="statistical-search">
        <div class="search-left">
          <el-date-picker
            v-model="timeArrRange"
            type="daterange"
            range-separator="-"
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.startDate')"
            :default-time="['00:00:00', '23:59:59']"
            value-format="timestamp"
          >
          </el-date-picker>
          <el-input v-model="form.taskNoStr" :placeholder="$t('common.placeholder.selectSomething', {0: $t('common.form.type.taskNo')})"></el-input>
          <el-input v-model="form.userNameStr" :placeholder="$t('event.setting.additional.component.statisticalDialog.pla2')"></el-input>
          <el-button type="primary" @click="onSearch">{{$t('common.base.search')}}</el-button>
        </div>
        <div class="search-right" v-if="isButtonDisplayed">     
          <a v-if="useExportUrl" :href="exportUrl">{{$t('common.base.export')}}</a>
          <a v-else @click="OpenExport">{{$t('common.base.export')}}</a>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        class="page-table statistical-table"
        :highlight-current-row="false"
        border
        header-row-class-name="page-table-header" 
        stripe
        tooltip-effect="dark"
        v-loading="loading">
        <el-table-column prop="taskNo" :label="$t('common.form.type.taskNo')" width="150">
          <template slot-scope="scope">
            <a @click="openTaskView(scope.row.taskId, scope.row.taskNo)">{{scope.row.taskNo}}</a>
          </template>
        </el-table-column>

        <!-- start 非工时记录列表数据 -->
        <template v-if="card.specialfrom != '工时记录'">
          <el-table-column  
            v-for="(column, index) in columns" 
            :key="`${column.field}_${index}`"
            :prop="column.fieldName" 
            :label="column.displayName" 
            :show-overflow-tooltip="true"
            :min-width="column.minWidth || '120px'">
            <template slot-scope="scope">
              <!-- start 自定义字段 -->
              <!-- start 多选 -->
              <template v-if="isMulti(column)">
                {{ (scope.row.taskCardInfo[column.fieldName] || []).join('，') }}
              </template>
              <!-- start 操作时间 -->
              <template v-else-if="column.fieldName === 'updateTime'">
                {{ scope.row.taskCardInfo[column.fieldName] | formatDate }}
              </template>
              <!-- end 操作时间 -->
                <!-- start 产品 -->
              <template v-else-if="column.fieldName === 'taskCardRelationProduct'">
                {{scope.row.taskCardInfo[column.fieldName]?scope.row.taskCardInfo[column.fieldName][0].name:''}}
              </template>
              <!-- end 产品 -->

              <!-- start 工单状态 -->
              <template v-else-if="column.fieldName === 'state'">
                {{ stateText(scope.row.taskCardInfo) || '' }}
              </template>
              <!-- end 工单状态 -->
              
              <!-- start 工单编号 -->
              <template v-else-if="column.fieldName === 'taskNo'">
                {{ scope.row.taskCardInfo[column.fieldName]  }}
              </template>
              <!-- end 工单编号 -->

              <!-- end 多选 -->
              <template v-else>
                {{ $formatFormField(column, scope.row, 'taskCardInfo') }}
              </template>
              <!-- end 自定义字段 -->
            </template>
          </el-table-column>
        </template>
        <!-- start 非工时记录列表数据 -->

        <!-- start 工时记录统计列表数据-->
        <template v-else>
          <el-table-column  
            v-for="(column, index) in columns" 
            :key="`${column.field}_${index}`"
            :prop="column.fieldName" 
            :label="column.displayName"
            :show-overflow-tooltip="column.showTooltip"
            :min-width="column.minWidth || '120px'">
            <template slot-scope="scope">
              <!-- start 多选 -->
              <template v-if="isMulti(column)">
                {{ (scope.row[column.fieldName] || []).join('，') }}
              </template>
              <!-- end 多选 -->

              <!-- start 开始结速时间 -->
              <template v-else-if="column.fieldName === 'startTime' || column.fieldName === 'endTime' || column.fieldName === 'operateTime'">
                {{scope.row[column.fieldName] | formatDate}}
              </template>
              <!-- end 开始结速时间 -->

              <template v-else-if="column.fieldName === 'startPositionState' || column.fieldName === 'endPositionState'">
                {{ scope.row[column.fieldName] === 1 ? $t('common.base.yes') : $t('common.base.no') }}
              </template>

              <template v-else>
                {{ $formatFormField(column, scope.row) }}
              </template>
            </template>
          </el-table-column>
        </template>  
        <!-- end 工时记录统计列表数据-->  
      </el-table>
      <div class="table-footer comment-list-table-footer">
        <div class="comment-list-table-footer-info task-flex task-ai">
          <i18n path="common.base.table.totalPiece">
            <span place="count" class="level-padding">{{totalElements || 0}}</span>
          </i18n>
          <div class="task-font14 task-c6 task-ml12">
            <i18n path="task.setting.taskAdditionalSetting.eachPageNum">
              <el-select
                place="count"
                v-model="form.pageSize"
                :placeholder="$t('common.placeholder.select')"
                @change="handleSizeChange(form.pageSize)"
                class="table-footer-select"
              >
                <el-option :label="10" :value="10"></el-option>
                <el-option :label="20" :value="20"></el-option>
                <el-option :label="50" :value="50"></el-option>
              </el-select>
            </i18n>
          </div>
        </div>
        <el-pagination
          v-if="this.tableData"
          class="comment-list-table-footer-pagination"
          background
          @current-change="jumpPage"
          @size-change="handleSizeChange"
          :page-size="form.pageSize"
          :current-page="form.pageNum"
          layout="prev, pager, next, jumper"
          :total="totalElements"
        >
        </el-pagination>
      </div>

    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onClose" >{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-modal>
   <!-- start 导出s -->
   <base-export-group
      ref="exportRef"
      :alert="exportAlert"

      :columns="exportColumn"
      :build-params="exportParamsBuild"

      :group="true"
      :validate="exportCountCheck"
      method="post"
      action="/excels/card/taskCardExport"
    />
    <!-- end 导出e -->
</div>
</template>
<script>
// api
import * as SettingTaskApi from '@src/api/SettingTaskApi';
// util
import { formatDate, objectToUrlParams, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import fieldUtil from './cardField';
import { checkButtonDisplayed } from '@src/util/dom';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import i18n from '@src/locales';
import TaskStateEnum from '@model/enum/TaskStateEnum.ts';
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';

export default {
  name: 'statistical-dialog',
  props: {
    card:{
      type: Object,
      default: () => ({})
    },
    // 导出数据， true 附加组件表单设置使用，false 选择导出列
    useExportUrl:{
      type: Boolean,
      default: true,
    }
  },
  data() {
    return {
      isButtonDisplayed: checkButtonDisplayed(),
      loading: true,
      visible: false,
      totalElements: 0,
      form: {
        cardId: '',
        pageNum: 1,
        pageSize: 10,
        timeRange: '', // 2020/11/11 - 2020/12/10
        taskNoStr: '',
        userNameStr: ''
      },
      tableData:[],
      cardFieldsData:[],
      timeArrRange:[],
      // 选择导出
      isOpenData,
      exportColumnList: [],
    };
  },
  filters: {
    formatDate(val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm')
    }
  },
  computed: {
    exportUrl(){
      const { form, card } = this
      const { taskNoStr, userNameStr } = form
      const params = {
        cardId: card.id,
        userNameStr,
        taskNoStr,
        ...this.disposeSubmitTime()
      }
      return `/setting/task/card/count/export?${objectToUrlParams(params)}`
    },
    /** 
    * @description 表头设置
    */
    columns() {
      let cardFields = this.cardFieldsData;
      if(cardFields.length > 0){
        // 工时记录
        if(this.card.specialfrom == '工时记录'){
          let fields = fieldUtil.toTableFields(cardFields, this.card.config);
          return fields.filter(field => field.enabled == 1);
        }
        // 备件清单/服务清单
        
        return fieldUtil.packCustomFields(cardFields)
        
      }
    },
    exportColumn() {
      const taskInfo = {
        label: i18n.t('common.task.TaskExportGroupTextEnum.task'),
        value: 'task',
        columns: [],
      }

      const cardInfo = {
        label: i18n.t('task.AdditionalInformation'),
        value: 'card',
        columns: [],
      }

      for(let item of this.exportColumnList){
        item.export = true;
        item.label = item.displayName;
        item.field = item.fieldName;
        item.value = item.fieldName;
        
        if(item.tableName === 'task'){
          taskInfo.columns.push(item);
        }else if(item.tableName === 'card' && item.formType !== FieldTypeMappingEnum.JsCodeBlock){
          cardInfo.columns.push(item);
        }
      }

      let column = [taskInfo, cardInfo].filter(item => {
        return item.columns && item.columns.length > 0;
      });

      return column
    }
  },
  mounted() {
    this.timeRange();
  },
  methods: {
    /** 工单状态*/
    stateText(value) {
      return TaskStateEnum.getNameForTask( value || {});
    },
    // 选择导出 Start
    OpenExport(){
      this.$refs.exportRef.open();
    },
    exportParamsBuild(checkedMap, ids){
      const {card, task} = checkedMap

      const { form } = this
      const { taskNoStr, userNameStr } = form
      const params = {
        cardId: this.card.id,
        userNameStr,
        taskNoStr,
        ...this.disposeSubmitTime()
      }

      return {
        taskFields: task.join(','),
        cardFields: card.join(','),
        cardId: this.card.id,
        searchModel: JSON.stringify(params),
        total: this.totalElements
      }
    },
    getTaskCardExportFields(){
      SettingTaskApi.getTaskCardExportFields({
        cardId: this.card.id
      })
      .then(res=>{
        if(res.success){
          this.exportColumnList = res.result;
          // 附加组件是关联工单并且开启展示系统字段处理
          const targetIndex = this.exportColumnList.findIndex(f => f.formType === 'related_task' && f.subCardFieldList?.length > 0 );  
          if (targetIndex !== -1) {
            const targetDataArray = this.exportColumnList[targetIndex].subCardFieldList || [];
            targetDataArray.forEach(f=>{
              f.tableName = 'card'
            })
            this.exportColumnList.splice(targetIndex + 1, 0, ...targetDataArray);
          }
        }
      })
    },
     /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    exportCountCheck(ids, max){
      return null
    },
    // 选择导出 End
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    disposeSubmitTime(){
      const [ startTime, endTime ] = this.timeArrRange || []
      return {
        startTime,
        endTime,
      }
    },
    valueAtt_href(field) {
      return JSON.parse(field)
    },
    /** 
    * @description 默认时间
    */
    timeRange() {
      this.timeArrRange = [+nearDateBy(1, 'month'), +dayTimeEnd()];
    },
    /** 
    * @description 查看工单详情
    */
    openTaskView(taskId, taskNo) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
        
      //   url: `/task/view/${taskId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        fromId
      })
    },

    /** 
    * @description 字段是否是多选类型
    */
    isMulti(field) {
      let { formType, setting = {}} = field;
      if (formType === 'selectMulti') return true;
      if (formType === 'select' && setting.isMulti) return true;
      return false;
    },
    /** 
    * @description 打开统计弹窗
    */
    openDialog() {
      this.visible = true;
      this.timeRange();

      this.$nextTick(()=>{
        if(this.card.id) {
          this.form.cardId = this.card.id;
          this.getCardFields()
          this.getCardCountReq();
          this.getTaskCardExportFields()
        }
      })
    },
    onClose(form) {
      this.visible = false;
      this.form = {
        pageNum: 1,
        pageSize: 10,
        timeRange: [],
        taskNoStr: '',
        userNameStr: ''    
      }
    },
    /** 
    * @description 搜索
    */
    onSearch() {
      this.form.pageNum = 1;
      this.getCardCountReq()
    },

    /**
     * @description 页大小改变操作
     * @param {Number} pageSize 页大小
     */
    handleSizeChange(pageSize) {
      this.form.pageSize = pageSize;
      this.form.pageNum = 1;
      this.getCardCountReq();
    },
    /**
     * @description 页码跳转
     * @param {Number} pageNum 页码
     */
    jumpPage(pageNum) {
      this.form.pageNum = pageNum;
      this.getCardCountReq();
    },

    // 获取统计Fields列表
    getCardFields() {
      SettingTaskApi.getCardFields({cardId:this.card.id}).then(res=>{
        const { code, message, result = [] } = res;
        if( code == 0 ){
          this.cardFieldsData = result.filter(item=> item.formType !== FieldTypeMappingEnum.JsCodeBlock);
 
          // 附加组件是关联工单并且开启展示系统字段处理
          const targetIndex = this.cardFieldsData.findIndex(f => f.formType === 'related_task' && f?.setting && Object.prototype.toString.call(f.setting) === '[object String]' && JSON.parse(f.setting).isShowSystemFields);  
          if (targetIndex !== -1) {
            const targetDataArray = this.cardFieldsData[targetIndex].subCardFieldList || [];
            this.cardFieldsData.splice(targetIndex + 1, 0, ...targetDataArray);
          }
        }
      }).catch(error=>({}))
    },

    // 获取统计列表
    getCardCountReq() {
      const params = {
        ...this.form,
        ...this.disposeSubmitTime(),
      }
      SettingTaskApi.getCardCount(params).then(res=>{
        const { status, total, message, list = [] } = res;
        this.totalElements = total;
        if(this.card.specialfrom != '工时记录'){  
          list.forEach(item=>{
            item.taskCardInfo = item.taskCardInfo ? JSON.parse(item.taskCardInfo) : {}
          })
        }
        this.tableData = list;
        this.loading = false;

      }).catch(error=>({ }))

    }
  },
};
</script>
<style lang="scss">
.statistical-dialog {
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 18px;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-body {
    padding: 20px;
    .base-modal-content{
      .statistical-search{
        display: flex;
        justify-content: space-between;
        .search-left{
          display: flex;
          justify-content: flex-start;
          .el-date-editor{
            margin-right: 12px;
            width: 256px !important;
          }
          .el-input{
            margin-right: 12px;
            width: 168px;
          }
        }
        .search-right{
          a{
            width: 58px;
            height: 32px;
           background: $color-primary-light-1;
            border-radius: 4px;
            border: 1px solid $color-primary-light-2;
            color: $color-primary-light-6;
            text-decoration: none;
            padding: 6px 10px;
            cursor: pointer;
          }
        }
      }
      .statistical-table{
        padding: 0;
        margin-top: 17px;  
        a{
          width: 100%;
          color: $color-primary-light-6;
          cursor: pointer;
          display: block;
          @include text-ellipsis();
        }
      }
      .table-footer{
        margin-top: 17px;
      }
      .el-table--border{
        border-bottom: 1px solid #ebeef5;
      }
    }
    

  }
}
</style>